﻿/*
 ***************************************************************************
 * Microsoft Visual C# .NET
 * 名称：       App_Input_HealthVisitPlanUpdForm
 * 类型：       控制层
 * 功能说明：   健康管家-家访计划维护页面
 * 作者：       黄鑫
 * 创建日期：   2007/09/13
 * 修改日期     修改者      修改内容
 * 
 * 
 * ---
 ***************************************************************************
*/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Shpm.System.Validator;
using Shpm.System.Web.Control;
using log4net;
using Shpm.App.Input.Bean;
using Shpm.App.Input.Dao;
using Shpm.App.Commons.Db.Beans.Master;
using Shpm.System;
using Shpm.App.Commons.Utils;

public partial class App_Input_HealthVisitPlanUpdForm : System.Web.UI.Page
{
    // log
    protected static ILog log = LogManager.GetLogger(typeof(App_Input_HealthVisitPlanUpdForm));


    // page load
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // 取得当前登录的医生id信息
            SysUserManager manager = new SysUserManager(Context);
            SysUserBean sysUserBean = manager.getSysUserBean();
            MstSysUserBean mstSysUserBean =
                sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
            MstEmployeeBean mstEmpBean =
                sysUserBean == null ? null : sysUserBean.getEmployeeBean();
            string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
            string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;
            string emplyRole = mstEmpBean == null ? "" : mstEmpBean.Role;
            string emplyJob = mstEmpBean == null ? "" : mstEmpBean.EmployeeJob;
            string emplyLevel = mstEmpBean == null ? "" : mstEmpBean.EmployeeLevel;

            ViewState["DOCTOR_ID"] = emplyId;
            ViewState["EMPLY_LEVEL"] = emplyLevel;

            // 接收传递参数为分页编号
            if (Context.Items.Contains("ParamPageIndex"))
            {
                ViewState["ParamPageIndex"] = Context.Items["ParamPageIndex"];
            }

            ViewState["VISITING_ID"] = Convert.ToString(Context.Items["VISITING_ID"]);
            ViewState["MEMBER_NO"] = Convert.ToString(Context.Items["MEMBER_NO"]);

            if (Context.Items.Contains("MemberNo"))
            {
                this.ViewState["MemberNo"] = Convert.ToString(Context.Items["MemberNo"]);
            }
            if (Context.Items.Contains("sDate"))
            {
                this.ViewState["sDate"] = Convert.ToString(Context.Items["sDate"]);
            }
            if (Context.Items.Contains("eDate"))
            {
                this.ViewState["eDate"] = Convert.ToString(Context.Items["eDate"]);
            }
            if (Context.Items.Contains("Sex"))
            {
                this.ViewState["Sex"] = Convert.ToString(Context.Items["Sex"]);
            }
            if (Context.Items.Contains("BuildingNo"))
            {
                this.ViewState["BuildingNo"] = Convert.ToString(Context.Items["BuildingNo"]);

            }
            if (Context.Items.Contains("FloorNo"))
            {
                this.ViewState["FloorNo"] = Convert.ToString(Context.Items["FloorNo"]);
            }
            if (Context.Items.Contains("Room"))
            {
                this.ViewState["Room"] = Convert.ToString(Context.Items["Room"]);
            }

            // 初始化控件
            initPageControls();
            bindSelectData(Convert.ToString(ViewState["VISITING_ID"]), Convert.ToString(ViewState["MEMBER_NO"]));
        }
        
    }

    // 登记按钮
    protected void btnOk_Click(object sender, EventArgs e)
    {
        try
        {
            // do validate check
            ComValidateChecker vd = new ComValidateChecker();
            vd.CheckItems.Add(new CheckRequired(txtBookDate.Text, new ComMessage("E0094", "下次家访日期")));
            vd.CheckItems.Add(new CheckRequired(txtFrequency.Text, new ComMessage("E0094", "家访间隔")));

            vd.CheckItems.Add(new CheckLong(txtFrequency.Text, new ComMessage("E0322", "家访间隔")));
            vd.CheckItems.Add(new CheckDate(txtBookDate.Text, "yyyy/MM/dd", new ComMessage("E0037", "下次家访日期")));
            vd.CheckItems.Add(new CheckDateRange(DateUtils.convertToString(DateTime.Today), Convert.ToString(txtBookDate.Text), new ComMessage("E0330", new string[] { "下次家访日期", "今天" })));

            if (!vd.DoValidator())
            {
                ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
                return;
            }

            // do insert update
            HealthVisitPlanDao dao = new HealthVisitPlanDao();
            HealthVisitPlanBean bean = new HealthVisitPlanBean();

            if (string.IsNullOrEmpty(Convert.ToString(ViewState["VISITING_ID"])))
            {
                // 登记
                bean.MemberNo = lblMemId.Text;
                bean.DoctorId = lblDocId.Text;
                bean.VisitingType = lstVisitingType.SelectedValue;
                bean.VisitingLevel = lstVisitingLevel.SelectedValue;
                bean.BespokeDate = DateUtils.convertToDate(txtBookDate.Text);
                bean.Frequency = Convert.ToInt32(txtFrequency.Text);
                bean.BespokeTime = lstBookTime.SelectedValue;
                bean.Memo = txtMemo.Text;
                bean.UserId = Convert.ToString(ViewState["DOCTOR_ID"]);
                Object retKey = dao.Insert(bean);
                if (retKey != null)
                {
                    this.ViewState["VISITING_ID"] = retKey.ToString();
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0001").ToString();
                }
            }
            else
            {
                // 更新
                bean.VisitingId = Convert.ToInt32(ViewState["VISITING_ID"]);

                //Check该计划是否已经完成
                bean.VisitingFlg = true;
                bean.CancelFlg = false;
                IList lstResult = dao.ChkResult(bean);
                if(lstResult.Count != 0)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0006").ToString().Replace("{0}", "家访计划");
                    return;
                }

                //Check该计划是否已经取消
                bean.VisitingFlg = false;
                bean.CancelFlg = true;
                lstResult = dao.ChkResult(bean);
                if (lstResult.Count != 0)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0007").ToString().Replace("{0}", "家访计划");
                    return;
                }

                // update
                bean.MemberNo = lblMemId.Text;
                bean.VisitingType = lstVisitingType.SelectedValue;
                bean.VisitingLevel = lstVisitingLevel.SelectedValue;
                bean.BespokeDate = DateUtils.convertToDate(txtBookDate.Text);
                bean.Frequency = Convert.ToInt32(txtFrequency.Text);
                bean.BespokeTime = lstBookTime.SelectedValue;
                bean.Memo = txtMemo.Text;
                bean.UserId = Convert.ToString(ViewState["DOCTOR_ID"]);
                dao.Update(bean);

                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0002").ToString();
            }
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }


    }


    // 返回按钮
    protected void btnBack_Click(object sender, EventArgs e)
    {
        string url = "~/App/Input/HealthVisitPlanSrhForm.aspx";
        Context.Items["ParamPageIndex"] = ViewState["ParamPageIndex"];
        Context.Items["MemberNo"] = ViewState["MemberNo"];
        Context.Items["sDate"] = ViewState["sDate"];
        Context.Items["eDate"] = ViewState["eDate"];
        Context.Items["Sex"] = ViewState["Sex"];
        Context.Items["BuildingNo"] = ViewState["BuildingNo"];
        Context.Items["FloorNo"] = ViewState["FloorNo"];
        Context.Items["Room"] = ViewState["Room"];
        ControllerUtils.Transfer(Context, url, true);
    }

    // bind data to controls
    private void bindSelectData(string visitingId, string memberNo)
    {
        HealthVisitPlanDao dao = new HealthVisitPlanDao();
        HealthVisitPlanBean bean = new HealthVisitPlanBean();

        if (!string.IsNullOrEmpty(Convert.ToString(visitingId)))
        {
            // get data
            bean.VisitingId = Convert.ToInt32(visitingId);
            bean.EmployeeLevel = "1";
            bean.SearchFlg = false;
            bean.EditFlg = false;
            bean = dao.Find(bean);
            if (bean != null)
            {
                lblDocId.Text = bean.DoctorId;
                lblMemId.Text = bean.MemberNo;
                lblMemName.Text = bean.MemberName;
                lblMemSex.Text = bean.MemberSex;
                lblMemTel.Text = bean.MemberTel;
                lblRoomId.Text = bean.ApartmentNo;
                lstVisitingType.SelectedValue = bean.VisitingType;
                lstVisitingLevel.SelectedValue = bean.VisitingLevel;
                txtFrequency.Text = Convert.ToString(bean.Frequency);
                txtBookDate.Text = DateUtils.convertToString(bean.BespokeDate.Value);
                lstBookTime.SelectedValue = bean.BespokeTime;
                txtMemo.Text = bean.Memo;
                return;
            }
        }

        // new visiting plan
        ViewState["VISITING_ID"] = "";
        bean = new HealthVisitPlanBean();
        bean.MemberNo = memberNo;
        bean.EmployeeLevel = "1";
        bean.SearchFlg = true;
        bean.EditFlg = false;
        bean = dao.Find(bean);
        if (bean != null)
        {
            lblDocId.Text = bean.DoctorId;
            lblMemId.Text = bean.MemberNo;
            lblMemName.Text = bean.MemberName;
            lblMemSex.Text = bean.MemberSex;
            lblMemTel.Text = bean.MemberTel;
            lblRoomId.Text = bean.ApartmentNo;
            txtFrequency.Text = Convert.ToString(bean.Frequency);
            txtBookDate.Text = DateUtils.convertToString(bean.BespokeDate.Value);
        }
        else
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "家访计划");
        }
    }

    // bind common catalog data 
    private void initPageControls()
    {
        HealthVisitPlanDao dao = new HealthVisitPlanDao();
        CommonDictionaryBean beanComDict = new CommonDictionaryBean();
        IList lstCat = null;

        // 家访类型
        log.Fatal("\n ***** get T_MEMBER_VISITING.VISITING_TYPE catalog *****");
        beanComDict.Catalog = "T_MEMBER_VISITING.VISITING_TYPE";
        lstCat = dao.FindByCatalog(beanComDict);
        lstVisitingType.Items.Clear();
        bindDataToListControl("lstVisitingType", lstCat);

        // 家访级别
        log.Fatal("\n ***** get T_MEMBER_VISITING.VISITING_LEVEL catalog *****");
        beanComDict.Catalog = "T_MEMBER_VISITING.VISITING_LEVEL";
        lstCat = dao.FindByCatalog(beanComDict);
        lstVisitingLevel.Items.Clear();
        bindDataToListControl("lstVisitingLevel", lstCat);

        // 预约时间
        lstBookTime.Items.Clear();
        for (int i = 1; i <= 24; i++)
        {
            string strTime;
            string strText;
            string strValue;

            if ((i + 8) < 10)
            {
                strTime = "0" + (i + 8) + ":00";
            }
            else
            {
                strTime = ((i + 8) % 24) + ":00";
            }
            strText = strTime;
            strValue = Convert.ToString((i + 8) % 24);
            ListItem item = new ListItem(strText, strText);
            lstBookTime.Items.Add(item);
        }
    }

    // bind db data to selected controls
    private void bindDataToListControl(string ControlId, IList LstData)
    {
        if (LstData == null || LstData.Count == 0) return;

        foreach (CommonDictionaryBean bean in LstData)
        {
            if (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is DropDownList)
            {
                ((DropDownList)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
            else if ((this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is CheckBoxList)
                || (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is RadioButtonList))
            {
                ((ListControl)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
        }
    }

    // 重置画面控件 返回新建状态
    private void resetFormControls()
    {
        if (lstVisitingType.Items.Count > 0) lstVisitingType.SelectedIndex = 0;
        if (lstVisitingLevel.Items.Count > 0) lstVisitingLevel.SelectedIndex = 0;
        txtBookDate.Text = "";
        if (lstBookTime.Items.Count > 0) lstBookTime.SelectedIndex = 0;
        txtMemo.Text = "";
        ViewState["VISITING_ID"] = "";
    }

    // before render
    void Page_PreRender(object sender, EventArgs e)
    {
        btnDel.Enabled = false;
        if (!string.IsNullOrEmpty(Convert.ToString(ViewState["VISITING_ID"])))
        {
            btnDel.Enabled = true;
        }
    }

    // 新建家访计划
    protected void btnNew_Click(object sender, EventArgs e)
    {
        resetFormControls();
    }

    // 删除按钮
    protected void btnDel_Click(object sender, EventArgs e)
    {
        try
        {
            HealthVisitPlanDao dao = new HealthVisitPlanDao();
            HealthVisitPlanBean bean = new HealthVisitPlanBean();
            if (!string.IsNullOrEmpty(Convert.ToString(ViewState["VISITING_ID"])))
            {
                bean.VisitingId  = Convert.ToInt32(ViewState["VISITING_ID"]);
                //Check该计划是否已经完成
                bean.VisitingFlg = true;
                bean.CancelFlg = false;
                IList lstResult = dao.ChkResult(bean);
                if (lstResult.Count != 0)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0006").ToString().Replace("{0}", "家访计划");
                    return;
                }
                //Check该计划是否已经取消
                bean.VisitingFlg = false;
                bean.CancelFlg = true;
                lstResult = dao.ChkResult(bean);
                if (lstResult.Count != 0)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0007").ToString().Replace("{0}", "家访计划");
                    return;
                }
                bean.UserId = Convert.ToString(ViewState["DOCTOR_ID"]);
                int delCnt = dao.Delete(bean);
                resetFormControls();
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0003").ToString();
            }
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }
    }    

}
